package mqConsumer

import (
	"encoding/json"
	"github.com/Sir-yuChen/funAnalyse/global"
	"github.com/Sir-yuChen/funAnalyse/model"
	"go.uber.org/zap"
	"time"
)

type BulletinConsumerHandle struct{}

type BulletinMsg struct {
	UserId                string `json:"userId"`
	BulletinMainTitle     string `json:"bulletinMainTitle"`
	BulletinSubtitleTitle string `json:"bulletinSubtitleTitle"`
	BulletinType          int64  `json:"bulletinType"`
	BulletinContent       string `json:"bulletinContent"`
	BulletinId            int    `json:"bulletinId"`
}

//RabbitMq Consumer 消费公共消息

// Consumer 消费消息 公告推送
func (t *BulletinConsumerHandle) Consumer(dataByte []byte) error {
	var msg BulletinMsg
	//1.json转map
	if err := json.Unmarshal(dataByte, &msg); err != nil {
		global.GVA_LOG.Error("BulletinConsumerHandle 数据转换异常", zap.Any("dataByte", dataByte), zap.Error(err))
		return err
	}
	var total int64
	//校验消息是否重复 同一条消息对同一个人在当天只能推送一次 select * from stock_user_bulletin where date(create_time) = curdate();
	err := global.GVA_DB.Model(model.StockUserBulletin{}).Where(" customer_id = ? AND bulletin_id = ? AND date(create_time) = curdate()", msg.UserId, msg.BulletinId).Count(&total).Error
	if err != nil {
		global.GVA_LOG.Error("BulletinConsumerHandle 校验当天推送消息是否重复", zap.Any("BulletinMsg", msg), zap.Error(err))
		return err
	}
	if total > 0 {
		global.GVA_LOG.Warn("BulletinConsumerHandle 用户当天已推送过该消息,注意无需再次推送", zap.Any("BulletinMsg", msg))
		return err
	}
	now := model.LocalTime(time.Now())
	userBulletin := model.StockUserBulletin{
		CustomerId:  msg.UserId,
		BulletinId:  int64(msg.BulletinId),
		Status:      1,
		CreateTime:  &now,
		LastUpdTime: &now,
	}
	//新增并推送
	if err := global.GVA_DB.Model(&userBulletin).Create(&userBulletin).Error; err != nil {
		global.GVA_LOG.Error("BulletinConsumerHandle 新增用户与消息之间关系异常", zap.Any("BulletinMsg", msg), zap.Error(err))
		return err
	}
	//todo 消息推送

	return nil
}

// FailAction 消费失败执行FailAction
func (t *BulletinConsumerHandle) FailAction(dataByte []byte) error {
	global.GVA_LOG.Error("BulletinConsumerHandle  推送消息异常 执行 FailAction", zap.Any("dataByte", dataByte))
	return nil
}
